package com.yuyou.fn.tradingservice.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.entity.SummerWinterDate;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.educational.service.ISummerWinterDateService;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.settlement.entity.MainAccount;
import com.yuyou.fn.settlement.service.IMainAccountService;
import com.yuyou.fn.tradingservice.entity.LeaseMessage;
import com.yuyou.fn.tradingservice.entity.PersonLeaseMessage;
import com.yuyou.fn.tradingservice.entity.ServiceProduct;
import com.yuyou.fn.tradingservice.mapper.LeaseMessageMapper;
import com.yuyou.fn.tradingservice.service.ILeaseMessageService;
import com.yuyou.fn.tradingservice.service.IPersonLeaseMessageService;
import com.yuyou.fn.tradingservice.service.IServiceProductService;
import com.yuyou.fn.tradingservice.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * LeaseMessage 表数据服务层接口实现类
 */
@Service
public class LeaseMessageServiceImpl extends SuperServiceImpl<LeaseMessageMapper, LeaseMessage, Long> implements ILeaseMessageService {


    @Resource
    private IServiceProductService serviceProductService;


    @Resource
    private IPersonLeaseMessageService personLeaseMessageService;


    @Resource
    private ICampusService campusService;

    @Resource
    private ISummerWinterDateService summerWinterDateService;

    @Resource
    private IMainAccountService mainAccountService;


    private static String[] weekNameArray = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};

    @Override
    public List<LeaseMessage> saveLeaseMessage(SysUser sysUser, List<LeaseMessagePriceVo> leaseMessagePriceVoList, ServiceProduct serviceProduct) {
        List<LeaseMessage> leaseMessageList = new ArrayList<LeaseMessage>(leaseMessagePriceVoList.size());

        for (LeaseMessagePriceVo leaseMessagePriceVo : leaseMessagePriceVoList) {
            if (leaseMessagePriceVo.getIsQuickly() == null) {
                throw new BusException("存在时间段未选择发布方式");
            }
            if (leaseMessagePriceVo.getStart() == null || leaseMessagePriceVo.getEnd() == null) {
                throw new BusException("开始结束时间必填");
            }
            if (leaseMessagePriceVo.getStart().getTime() > leaseMessagePriceVo.getEnd().getTime()) {
                throw new BusException("开始必须小于结束时间");
            }
            if (leaseMessagePriceVo.getIsQuickly()==1){
                Campus campus=campusService.findById(serviceProduct.getCampusId());
                SummerWinterDate summerWinterDate=summerWinterDateService.findByAreaTeamIdAndYear(campus.getAreaTeamId(),leaseMessagePriceVo.getYear());
                if (summerWinterDate==null){
                    throw new BusException(leaseMessagePriceVo.getYear()+"年的寒暑假时间未设置，请前往设置");
                }
            }

            for (LeaseMessagePriceVo checkLeaseMessagePriceVo : leaseMessagePriceVoList) {
                if(checkLeaseMessagePriceVo.equals(leaseMessagePriceVo)){
                    continue;
                }
                if (leaseMessagePriceVo.getStart().getTime()<=checkLeaseMessagePriceVo.getEnd().getTime() && leaseMessagePriceVo.getEnd().getTime()>=checkLeaseMessagePriceVo.getStart().getTime()){
                    throw new BusException(Utils.formatDate(leaseMessagePriceVo.getStart(),"yyyy-MM-dd")+"到"+Utils.formatDate(leaseMessagePriceVo.getEnd(),"yyyy-MM-dd")+"与"+Utils.formatDate(checkLeaseMessagePriceVo.getStart(),"yyyy-MM-dd")+"到"+Utils.formatDate(checkLeaseMessagePriceVo.getEnd(),"yyyy-MM-dd")+"时间冲突");
                }
            }

            LeaseMessage leaseMessage = new LeaseMessage();
            leaseMessage.setCampusId(serviceProduct.getCampusId());
            leaseMessage.setCampusName(serviceProduct.getCampusName());
            leaseMessage.setProductId(serviceProduct.getProductId());
            leaseMessage.setRoomId(serviceProduct.getRoomId());
            leaseMessage.setRoomName(serviceProduct.getRoomName());
            leaseMessage.setSellerId(serviceProduct.getSellerId());
            leaseMessage.setSellerPhoneNo(serviceProduct.getSellerPhoneNo());
            leaseMessage.setSellerName(serviceProduct.getSellerName());
            leaseMessage.setCreateTime(TimeUtils.now());
            leaseMessage.setUpdateTime(TimeUtils.now());
            leaseMessage.setCategoryId(serviceProduct.getCategoryId());
            leaseMessage.setCategoryName(serviceProduct.getCategoryName());
            leaseMessage.setStatus(serviceProduct.getStatus());
            leaseMessage.setStart(leaseMessagePriceVo.getStart());
            leaseMessage.setEnd(leaseMessagePriceVo.getEnd());
            leaseMessage.setsWHourPrice(leaseMessagePriceVo.getsWHourPrice());
            leaseMessage.setsWDayPrice(leaseMessagePriceVo.getsWDayPrice());
            leaseMessage.setWeekendHourPrice(leaseMessagePriceVo.getWeekendHourPrice());
            leaseMessage.setWeekendDayPrice(leaseMessagePriceVo.getWeekendDayPrice());
            leaseMessage.setWorkingDayPrice(leaseMessagePriceVo.getWorkingDayPrice());
            leaseMessage.setWorkingHourPrice(leaseMessagePriceVo.getWorkingHourPrice());
            leaseMessage.setMonthPrice(leaseMessagePriceVo.getMonthPrice());
            leaseMessage.setYearPrice(leaseMessagePriceVo.getYearPrice());
            String timeDesc=Utils.formatDate(leaseMessagePriceVo.getStart(),"yyyy-MM-dd")+"到"+Utils.formatDate(leaseMessagePriceVo.getEnd(),"yyyy-MM-dd");
            leaseMessage.setTimeDesc(timeDesc);
            leaseMessage.setProfitMainAccountId(serviceProduct.getProfitMainAccountId());
            leaseMessageList.add(leaseMessage);
        }
        leaseMessageList=this.canLease(sysUser,leaseMessageList,serviceProduct);
        if (leaseMessageList.size() > 0) {
            this.insertBatch(leaseMessageList);
        }
        return leaseMessageList;
    }

    @Override
    public List<LeaseMessage> canLease(SysUser sysUser, List<LeaseMessage> leaseMessageList, ServiceProduct serviceProduct) {
        List<LeaseMessage> newLeaseMessageList=new ArrayList<LeaseMessage>();
        Boolean noHave = serviceProductService.checkHaveAllRoomTime(serviceProduct.getProfitMainAccountId(),serviceProduct.getCampusId());//serviceProductService.checkHaveRoom(sysUser, serviceProduct.getCampusId(), serviceProduct.getRoomId());
        MainAccount mainAccount=mainAccountService.findById(serviceProduct.getProfitMainAccountId());
        for (LeaseMessage leaseMessage : leaseMessageList) {
            Date yearDate=TimeUtils.changeDateByNum(TimeUtils.addYearByNum(leaseMessage.getStart(),1),-1);
            if (yearDate.getTime()<=leaseMessage.getEnd().getTime() && leaseMessage.getYearPrice()==null){
                throw new BusException(leaseMessage.getTimeDesc()+"发布时间段超过一年，每年价格必填");
            }
            Date monthDate=TimeUtils.changeDateByNum(TimeUtils.addMonthByNum(leaseMessage.getStart(),1),-1);
            if (monthDate.getTime()<=leaseMessage.getEnd().getTime() && leaseMessage.getMonthPrice()==null){
                throw new BusException(leaseMessage.getTimeDesc()+"发布时间段超过一个月，每月价格必填");
            }
            LeaseMessageQueryVo leaseMessageQueryVo = new LeaseMessageQueryVo();
            leaseMessageQueryVo.setEndGreateStart(leaseMessage.getEnd());
            leaseMessageQueryVo.setStartLessEnd(leaseMessage.getStart());
            leaseMessageQueryVo.setStatus(1);
            leaseMessageQueryVo.setRoomId(leaseMessage.getRoomId());
            leaseMessageQueryVo.setProfitMainAccountId(leaseMessage.getProfitMainAccountId());
            List<LeaseMessage> allReleasedLeaseMessages = this.findLeaseMessage(leaseMessageQueryVo);
            for (LeaseMessage selfLeaseMessage:leaseMessageList){
                if(selfLeaseMessage.equals(leaseMessage)){
                    continue;
                }
                if (leaseMessage.getStart().getTime()<=selfLeaseMessage.getEnd().getTime() && leaseMessage.getEnd().getTime()>=selfLeaseMessage.getStart().getTime()){
                    throw new BusException(leaseMessage.getTimeDesc() +"与一起发布的"+selfLeaseMessage.getTimeDesc()+"冲突");
                }
            }
            for (LeaseMessage checkLeaseMessage:allReleasedLeaseMessages){
                if (leaseMessage.getStart().getTime()<=checkLeaseMessage.getEnd().getTime() && leaseMessage.getEnd().getTime()>=checkLeaseMessage.getStart().getTime()){
                    throw new BusException(leaseMessage.getTimeDesc() +"与原先其他发布的"+checkLeaseMessage.getTimeDesc()+"冲突");
                }
            }
            BitSet leaseMessageBitSet = new BitSet();
            leaseMessageBitSet.set(TimeUtils.toMini(leaseMessage.getStart()),TimeUtils.toMini(TimeUtils.changeDateByNum(leaseMessage.getEnd(), 1)));
            if (noHave) {
                String sourcePersonLeaseIds=null;
                PersonLeaseQueryVo personLeaseQueryVo = new PersonLeaseQueryVo();
                personLeaseQueryVo.setBuyerId(sysUser.getUserId());//用户购买
                personLeaseQueryVo.setLeaseState(1);
                personLeaseQueryVo.setPayMainAccountId(serviceProduct.getProfitMainAccountId());//收益主体购买
                personLeaseQueryVo.setRoomId(serviceProduct.getRoomId());
                personLeaseQueryVo.setStartLessEnd(leaseMessage.getStart());
                personLeaseQueryVo.setEndGreateStart(leaseMessage.getEnd());
                List<PersonLeaseMessage> personLeaseMessageList = personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);
                List<Long> personLeaseIds=BeanUtils.toList(personLeaseMessageList,"personLeaseId");
                sourcePersonLeaseIds=StringUtils.join(personLeaseIds,",");
                BitSet personLeaseMessageBitSet = new BitSet();
                List<String> confictIdsList=new ArrayList<String>();
                for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
                    personLeaseMessageBitSet.set(TimeUtils.toMini(personLeaseMessage.getStart()), TimeUtils.toMini(TimeUtils.changeDateByNum(personLeaseMessage.getEnd(), 1)));
                    String confictIds=personLeaseMessage.getConfictIds();
                    if (StringUtils.isNotEmpty(confictIds)){
                        confictIdsList.add(confictIds);
                    }
                }
                if (confictIdsList.size()>0){
                    String str=StringUtils.join(confictIdsList,",");
                    List<PersonLeaseMessage> noHavePersonLeaseMessageList=personLeaseMessageService.findByIds(Utils.toLongIds(str));
                    for (PersonLeaseMessage noHavePersonLeaseMessage:noHavePersonLeaseMessageList){
                        if (leaseMessage.getStart().getTime()<=noHavePersonLeaseMessage.getEnd().getTime() && leaseMessage.getEnd().getTime()>=noHavePersonLeaseMessage.getStart().getTime()){
                            throw new BusException(leaseMessage.getTimeDesc() + "存在时间不在("+mainAccount.getName()+")拥有的时间段里，请查看时间占用表");
                        }
                    }
                }
                leaseMessageBitSet.andNot(personLeaseMessageBitSet);
                if (leaseMessageBitSet.cardinality() != 0) {
                    throw new BusException(leaseMessage.getTimeDesc() + "存在时间不在("+mainAccount.getName()+")拥有的时间段里，请查看时间占用表");
                }
                leaseMessage.setSourcePersonLeaseIds(sourcePersonLeaseIds);
            }
            newLeaseMessageList.add(leaseMessage);
        }
        return newLeaseMessageList;
    }

    @Override
    public List<TimeStampLong> fillLeaseMessage(LeaseMessage leaseMessage, ServiceProduct serviceProduct) {

        leaseMessage.setCampusId(serviceProduct.getCampusId());
        leaseMessage.setCampusName(serviceProduct.getCampusName());
        leaseMessage.setProductId(serviceProduct.getProductId());
        leaseMessage.setRoomId(serviceProduct.getRoomId());
        leaseMessage.setRoomName(serviceProduct.getRoomName());
        leaseMessage.setSellerId(serviceProduct.getSellerId());
        leaseMessage.setSellerPhoneNo(serviceProduct.getSellerPhoneNo());
        leaseMessage.setSellerName(serviceProduct.getSellerName());
        leaseMessage.setCreateTime(TimeUtils.now());
        leaseMessage.setUpdateTime(TimeUtils.now());
        leaseMessage.setCategoryId(serviceProduct.getCategoryId());
        leaseMessage.setCategoryName(serviceProduct.getCategoryName());
        leaseMessage.setStatus(serviceProduct.getStatus());
        return this.getTimeStampLongList(leaseMessage);
    }

    @Override
    public LeaseDetailVo findLeaseDetailVo(LeaseMessage leaseMessage) {
        LeaseDetailVo leaseDetailVo = new LeaseDetailVo();
        ServiceProduct serviceProduct = serviceProductService.findById(leaseMessage.getProductId());
        BeanUtils.copyProperties(leaseDetailVo, serviceProduct);
        BeanUtils.copyProperties(leaseDetailVo, leaseMessage);
        return leaseDetailVo;
    }

    @Override
    @Transactional
    public void offLease(Long leaseId, Integer status, Long productId) {
        LeaseMessage leaseMessage = new LeaseMessage();
        leaseMessage.setLeaseId(leaseId);
        leaseMessage.setStatus(status);
        leaseMessage.setUpdateTime(TimeUtils.now());
        updateSelectiveById(leaseMessage);

        LeaseMessageQueryVo leaseMessageQueryVo = new LeaseMessageQueryVo();
        leaseMessageQueryVo.setProductId(productId);
        leaseMessageQueryVo.setStatus(1);
        List<LeaseMessage> leaseMessageList = this.findLeaseMessage(leaseMessageQueryVo);
        if (leaseMessageList == null || leaseMessageList.size() <= 0) {
            serviceProductService.changeStatus(productId, status);
        }
    }

    @Override
    public List<LeaseMessage> findLeaseMessage(LeaseMessageQueryVo leaseMessageQueryVo) {
        Example<LeaseMessage> example = LeaseMessage.createExample();
        Example.Criteria criteria = example.createCriteria();

        if (leaseMessageQueryVo.getLeaseId() != null) {
            criteria.andEqualTo("leaseId", leaseMessageQueryVo.getLeaseId());
        }
        if (leaseMessageQueryVo.getProfitMainAccountId()!=null){
            criteria.andEqualTo("profitMainAccountId",leaseMessageQueryVo.getProfitMainAccountId());
        }

        if (leaseMessageQueryVo.getTimeType() != null) {
            criteria.andEqualTo("timeType", leaseMessageQueryVo.getTimeType());
        }

        if (leaseMessageQueryVo.getDateType() != null) {
            criteria.andEqualTo("dateType", leaseMessageQueryVo.getDateType());
        }


        if (leaseMessageQueryVo.getRoomId() != null) {
            criteria.andEqualTo("roomId", leaseMessageQueryVo.getRoomId());
        }
        if (StringUtils.isNotEmpty(leaseMessageQueryVo.getRoomName())) {
            criteria.andLike("roomName", "%" + leaseMessageQueryVo.getRoomName() + "%");
        }

        if (leaseMessageQueryVo.getDateQueryCode() != null && leaseMessageQueryVo.getDateQueryCode() == 1 && leaseMessageQueryVo.getStart() != null && leaseMessageQueryVo.getEnd() != null) {
            criteria.andBetween("start", leaseMessageQueryVo.getStart(), leaseMessageQueryVo.getEnd());
        }
        if (leaseMessageQueryVo.getCategoryId() != null) {
            criteria.andEqualTo("categoryId", leaseMessageQueryVo.getCategoryId());
        }


        if (StringUtils.isNotEmpty(leaseMessageQueryVo.getStatusStr())) {
            String[] statusArr = leaseMessageQueryVo.getStatusStr().split(",");
            criteria.andIn("status", Arrays.asList(statusArr));
        }

        if (leaseMessageQueryVo.getStatus() != null) {
            criteria.andEqualTo("status", leaseMessageQueryVo.getStatus());
        }

        if (leaseMessageQueryVo.getGreateEndTime() != null) {
            criteria.andGreaterThan("end", leaseMessageQueryVo.getGreateEndTime());
        }

        if (leaseMessageQueryVo.getLessEndTime() != null) {
            criteria.andLessThan("end", leaseMessageQueryVo.getLessEndTime());
        }

        if (leaseMessageQueryVo.getGreateStartTime() != null) {
            criteria.andGreaterThan("start", leaseMessageQueryVo.getGreateStartTime());
        }

        if (leaseMessageQueryVo.getProductId() != null) {
            criteria.andEqualTo("productId", leaseMessageQueryVo.getProductId());
        }
        if (leaseMessageQueryVo.getSellerId() != null) {
            criteria.andEqualTo("sellerId", leaseMessageQueryVo.getSellerId());
        }
        if (leaseMessageQueryVo.getEndGreateStart() != null) {
            criteria.andLessThanOrEqualTo("start", leaseMessageQueryVo.getEndGreateStart());
        }
        if (leaseMessageQueryVo.getStartLessEnd() != null) {
            criteria.andGreaterThanOrEqualTo("end", leaseMessageQueryVo.getStartLessEnd());
        }

        if (StringUtils.isNotEmpty(leaseMessageQueryVo.getEndTimeGreateStartTime())) {
            criteria.andLessThanOrEqualTo("startTime", leaseMessageQueryVo.getEndTimeGreateStartTime());
        }
        if (StringUtils.isNotEmpty(leaseMessageQueryVo.getStartTimeLessEndTime())) {
            criteria.andGreaterThanOrEqualTo("endTime", leaseMessageQueryVo.getStartTimeLessEndTime());
        }


        if (leaseMessageQueryVo.getWeekNum() != null) {
            criteria.andEqualTo("weekNum", leaseMessageQueryVo.getWeekNum());
        }

        if (leaseMessageQueryVo.getOrderByStart() != null) {
            example.orderBy("start");
        }
        if (leaseMessageQueryVo.getOrderByStartTime() != null) {
            example.orderBy("startTime");
        }

        if (StringUtils.isNotEmpty(leaseMessageQueryVo.getOrderByTimeTypeDesc())) {
            example.orderBy("timeType").desc();
        }

    /*    if (leaseMessageQueryVo.getTeamId() != null && leaseMessageQueryVo.getTeamId() != 0) {
            criteria.andEqualTo("busTeamId", leaseMessageQueryVo.getTeamId());
        } else {
            if (leaseMessageQueryVo.getAreaTeamId() != null) {
                criteria.andEqualTo("areaTeamId", leaseMessageQueryVo.getAreaTeamId());
            }
        }*/
        return findListByExample(example);
    }


    @Override
    public List<TimeStampLong> getTimeStampLongList(LeaseMessage leaseMessage) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        int timeInterval = 1;
        if (leaseMessage.getTimeType() == 0) {
            timeInterval = 1;
        } else if (leaseMessage.getTimeType() == 1) {
            timeInterval = 7;
        } else if (leaseMessage.getTimeType() == 2) {
            timeInterval = 30;
        } else if (leaseMessage.getTimeType() == 3) {
            timeInterval = 365;
        }
        if (StringUtils.isEmpty(leaseMessage.getStartTime())) {
            if (leaseMessage.getTimeType() == -1) {
                leaseMessage.setStartTime("08:00");
            } else {
                leaseMessage.setStartTime("00:00");
            }


        }
        if (StringUtils.isEmpty(leaseMessage.getEndTime())) {
            if (leaseMessage.getTimeType() == -1) {
                leaseMessage.setStartTime("22:00");
            } else {
                leaseMessage.setStartTime("24:00");
            }
        }

        if (leaseMessage.getStart().after(leaseMessage.getEnd())) {
            throw new BusException(leaseMessage.getTimeDesc() + "开始日期必须小于结束日期");
        }


        if (leaseMessage.getStartTime().compareTo(leaseMessage.getEndTime()) >= 0) {
            throw new BusException(leaseMessage.getTimeDesc() + "开始时间必须小于结束时间");
        }


        List<TimeStampLong> timeStampLongList = new ArrayList<TimeStampLong>();
        /*整卖的时间段*/
        int days = TimeUtils.daysOfTwo(leaseMessage.getStart(), leaseMessage.getEnd()) + 1;
        if (leaseMessage.getDetachable() == 0) {
            TimeStampLong timeStampLong = new TimeStampLong();
            Date startDate = leaseMessage.getStart();
            Date endDate = leaseMessage.getEnd();
            endDate = TimeUtils.changeDateByNum(endDate, 1);//时间戳，结束日期应该到第二天0.00
            timeStampLong.setStartTimeStamp(TimeUtils.toMini(startDate));
            timeStampLong.setEndTimeStamp(TimeUtils.toMini(endDate));
            timeStampLongList.add(timeStampLong);
            if (leaseMessage.getUnitNum() == null) {
                BigDecimal unitNum = BigDecimal.ZERO;
                unitNum = new BigDecimal(days).divide(new BigDecimal(timeInterval), 3, BigDecimal.ROUND_HALF_UP);
                leaseMessage.setUnitNum(unitNum);
            }
        } else {
            try {
                Integer dateType = leaseMessage.getDateType();
                Date startDate = leaseMessage.getStart();
                Date endDate = leaseMessage.getEnd();
                Integer weekNum = leaseMessage.getWeekNum();
                String startTime = leaseMessage.getStartTime();
                String endTime = leaseMessage.getEndTime();
                if (dateType == 1) {
                    int firstWeek = TimeUtils.getWeekOfDate(startDate);
                    int dataNum = 0;
                   /* if (firstWeek != weekNum) {
                        dataNum = 6 - firstWeek + weekNum + 1;
                    }*/
                    if (weekNum > firstWeek) {
                        dataNum = weekNum - firstWeek;
                    } else if (weekNum < firstWeek) {
                        dataNum = 6 - firstWeek + weekNum + 1;
                    }
                    if (dataNum != 0) {
                        startDate = TimeUtils.changeDateByNum(startDate, dataNum);
                    }
                    BigDecimal unitNum = BigDecimal.ZERO;
                    while (startDate.before(endDate) || startDate.equals(endDate)) {
                        String str = sdf.format(startDate);
                        String startStr = str + " " + startTime;
                        String endStr = str + " " + endTime;
                        if (leaseMessage.getTimeType() == -1) {
                            Integer startTimeNum = Integer.parseInt(startTime.split(":")[0]);
                            Integer endTimeNum = Integer.parseInt(endTime.split(":")[0]);
                            unitNum = unitNum.add(new BigDecimal(endTimeNum - startTimeNum));
                        } else {
                            unitNum = unitNum.add(BigDecimal.ONE);
                        }

                        TimeStampLong timeStampLong = new TimeStampLong();
                        timeStampLong.setStartTimeStamp(TimeUtils.toMini(sdf1.parse(startStr)));
                        timeStampLong.setEndTimeStamp(TimeUtils.toMini(sdf1.parse(endStr)));
                        startDate = TimeUtils.changeDateByNum(startDate, 7);
                        timeStampLongList.add(timeStampLong);
                    }
                    if (leaseMessage.getUnitNum() == null) {
                        leaseMessage.setUnitNum(unitNum);
                    }
                } else {
                    BigDecimal unitNum = BigDecimal.ZERO;
                    while (startDate.before(endDate) || startDate.equals(endDate)) {
                        String str = sdf.format(startDate);

                        if (leaseMessage.getTimeType() == -1) {
                            Integer startTimeNum = Integer.parseInt(startTime.split(":")[0]);
                            Integer endTimeNum = Integer.parseInt(endTime.split(":")[0]);
                            unitNum = unitNum.add(new BigDecimal(endTimeNum - startTimeNum));
                        } else {
                            unitNum = unitNum.add(BigDecimal.ONE);
                        }


                        String startStr = str + " " + startTime;
                        String endStr = str + " " + endTime;
                        TimeStampLong timeStampLong = new TimeStampLong();
                        timeStampLong.setStartTimeStamp(TimeUtils.toMini(sdf1.parse(startStr)));
                        timeStampLong.setEndTimeStamp(TimeUtils.toMini(sdf1.parse(endStr)));
                        timeStampLongList.add(timeStampLong);
                        startDate = TimeUtils.changeDateByNum(startDate, 1);
                    }
                    if (leaseMessage.getUnitNum() == null) {
                        leaseMessage.setUnitNum(unitNum);
                    }
                }
            } catch (ParseException e) {
                throw new BusException("分析时间出错");
            }
        }
        if (leaseMessage.getUnitNum() == null || leaseMessage.getUnitNum().equals(BigDecimal.ZERO)) {
            throw new BusException(leaseMessage.getTimeDesc() + "所选时间段不包含出租的时间");
        }


        return timeStampLongList;
    }



    @Override
    @Transactional
    public void deleteLeaseById(Long leaseId) {
        LeaseMessage leaseMessage = this.findById(leaseId);
        deleteById(leaseId);
        LeaseMessageQueryVo leaseMessageQueryVo = new LeaseMessageQueryVo();
        leaseMessageQueryVo.setProductId(leaseMessage.getProductId());
        List<LeaseMessage> leaseMessageList = this.findLeaseMessage(leaseMessageQueryVo);
        if (leaseMessageList == null || leaseMessageList.size() <= 0) {
            serviceProductService.deleteById(leaseMessage.getProductId());
        }
    }



    @Override
    public void deleteByProductIds(List<Long> productIds) {
        if(productIds == null || productIds.isEmpty() ){
            throw new NullPointerException();
        }
        Example<LeaseMessage> leaseMessageExample = LeaseMessage.createExample();
        Example.Criteria criteria = leaseMessageExample.createCriteria();
        criteria.andIn("productId", productIds);
        deleteByExample(leaseMessageExample);
    }

    @Override
    public void updateStatusByProductId(Long productId, Integer status) {
        Example<LeaseMessage> leaseMessageExample = LeaseMessage.createExample();
        Example.Criteria criteria = leaseMessageExample.createCriteria();
        criteria.andEqualTo("productId", productId);

        LeaseMessage leaseMessage = new LeaseMessage();
        leaseMessage.setStatus(status);
        this.updateSelectiveByExample(leaseMessage, leaseMessageExample);
    }
}